﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using BOMS.Utility.DATA;

namespace BOMS.WebUI.Web.WebTool
{
    public partial class ImportTextData : System.Web.UI.Page
    {
        public string UserName
        {
            get {
                return Web.Common.GetCurrentUserNameChz();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {               
                BindRepeater();
            }
        }

        void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item ||
                e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Model.M_UploadData model = e.Item.DataItem as Model.M_UploadData;

                //状态
                Literal ltrStatus = e.Item.FindControl("ltrStatus") as Literal;//<%#Eval("Status")%>
                if (ltrStatus != null)
                {
                    ltrStatus.Text = GetStatusStr(model.Status);
                }
                
                //操作
                Button btn = e.Item.FindControl("btnImport") as Button;
                Button btnDel = e.Item.FindControl("btnDel") as Button;
                if (model.Status == 10)
                {
                    btn.Enabled = true;
                    btn.Attributes["onlick"] = "return ConfirmData();";

                    btnDel.Enabled = true;
                    btnDel.Attributes["onclick"] = "return confirm('真的要删除吗？');";
                    //btn.Click += new EventHandler(btn_Click);
                }
                else
                {
                    btn.Enabled = false;
                    btnDel.Enabled = false;
                }
            }
            
        }
        protected void btnDel_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            HiddenField hdf = btn.NamingContainer.FindControl("hdfID") as HiddenField;
            int Id = int.Parse(hdf.Value);
            Model.M_UploadData model = new BLL.M_UploadData().GetModel(Id);
            string vPath = model.FilePath;
            string physiPath = Server.MapPath(vPath);

            //删除
            new BLL.M_UploadData().Delete(model.ID);
            File.Delete(physiPath);
            Common.Alert(this, "已删除");
            //重新绑定数据
            BindRepeater();
            

        }
        protected void btn_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            HiddenField hdf = btn.NamingContainer.FindControl("hdfID") as HiddenField;
            int Id = int.Parse(hdf.Value);
            Model.M_UploadData model = new BLL.M_UploadData().GetModel(Id);
            string vPath = model.FilePath;
            string physiPath= Server.MapPath(vPath);
            int RecordCnt = ReadFileAndImportDatabase(physiPath, model);
            Common.Alert(this, "导入成功(共"+RecordCnt+"条)");
            //重新绑定数据
            BindRepeater();
           
        }
        int ReadFileAndImportDatabase(string physiPath, Model.M_UploadData model)
        {
            if(File.Exists(physiPath))
            {

                using(FileStream fs = new FileStream(physiPath,FileMode.Open))
                {
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0,(int)fs.Length);
                    int RecordCnt = 0;
                    int start = 0;
                    int pos = 0;

                    byte[] NewLineSymbol =new byte[] {13,10};//寻找换行符
                    while (start < fs.Length && SearchOnePackPos(buffer, start, ref pos))
                    {   
                        int Len = pos-start-2;
                        byte[] oneBuf =new byte[Len + 6];//总长度(依最新的CET工程师给的TCP传输包协议)包含头3字节、尾3字节
                        //手工填写前面3个字节
                        oneBuf[0] = 0xA * 16 + 0xA;
                        oneBuf[1] = (byte)(Len / 256);
                        oneBuf[2] = (byte)(Len % 256);
                        Array.Copy(buffer, start, oneBuf, 3, Len);
                        if (oneBuf.Length < 50)
                        {
                            throw new Exception("太短");
                        }
                        //准备参数
                        ProtocolPack pack = BuildData.Converting(oneBuf);
                        string xml = BuildData.OutputXML(pack);
                        string ip = model.IP;
                        string mac = model.EquipMac;
                        DateTime dtm = pack.Dtm;
                        //导入一条数据
                        DAL.DALUti.ImportEquipData(ip, mac, dtm, xml);
                        RecordCnt++;
                        //开始新的起点
                        start = pos;
                    }

                    int newStatus = 20;//表示已经导入
                    string OperateDescr = string.Format("{0} {1} {2}",
                        DateTime.Now.ToString("yyyyMMdd HH:mm"),
                        Common.GetCurrentUserNameChz(),
                        "导入文本到数据库" + RecordCnt+"条"
                        );
                    new BLL.M_UploadData().UpdateFileStatus(model.ID, newStatus, OperateDescr);
                    return RecordCnt;
                }
            }
            return 0;
        }
        public bool SearchOnePackPos(byte[] buffer, int startPos, ref int destPos)
        {
            //用公式【16+40*组数+12*电池节数+2 】求一个包的长度
            int PackLength = 16 ;//头部16字节
            int grpCnt = buffer[startPos + 6];
            PackLength += grpCnt * 40;//电池组信息40字节
            int[] batCntArr = new int[grpCnt];
            for (int i = 1; i <= grpCnt; i++)
            {
                batCntArr[i-1] = buffer[startPos + 6 + i];//组内电池数；
                PackLength += batCntArr[i-1] * 12;//每块电池占12字节
            }
            destPos = startPos + PackLength + 2;//另：包尾2个字节（ox0D0A）
            return destPos <= buffer.Length;
        }

        //在buffer中查找二进制字节序列key，找到返回1，未找到返回0
        public bool SearchByte(byte[] buffer, byte[] key, int startPos, ref int pos)
        {
            int i = startPos;
            int tem_pos = 0;
            bool found1 = false;
            int found2 = 0;
            do
            {
                for (int j = 0; j < key.Length; j++)
                {
                    if (buffer[i] == key[j])
                    {
                        if (j == 0)
                        {
                            found1 = true;
                            tem_pos = i;
                        }
                        else
                            found2 = 1;
                        i = i + 1;
                    }
                    else
                    {
                        if (j == 0)
                            found1 = false;
                        else
                            found2 = 2;
                    }
                    if (found1 == false)
                    {
                        i = i + 1;
                        break;
                    }
                    if ((found2 == 2))
                    {
                        i = i - j + 1;
                        found1 = false;
                        found2 = 0;
                        break;
                    }

                    if ((found1 == true) && (found2 == 1) && (j == (key.Length - 1))) //匹配上了
                    {
                        pos = i - (key.Length);
                        return true;
                    }
                }
            }
            while (i < buffer.Length);
            return false;
        }

        string GetStatusStr(int? n)
        {
            if (n.HasValue)
            {
                if (n == 10)
                {
                    return "未导入";
                }
                else if (n == 20)
                {
                    return "已导入";
                }
            }
            return "未知";
        }
        void BindRepeater()
        {
            int pageSize = Pager1.PageSize;
            int CurPageIdx = Pager1.CurrentPageIndex;
            int RecordCount ;
            List<Model.M_UploadData> list = new BLL.M_UploadData().GetListFromPage("", "ID DESC", pageSize, CurPageIdx, out RecordCount);
            Pager1.RecordCount = RecordCount;
            Repeater1.DataSource = list;
            Repeater1.ItemDataBound += new RepeaterItemEventHandler(Repeater1_ItemDataBound);
            Repeater1.DataBind();
        }
        protected void Pager1_PageChanged(object sender, EventArgs e)
        {
            BindRepeater();
        }
    }
}